package com.example.project.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.example.project.entity.IssueComment;
import com.example.project.entity.IssueCommentAttachment;
import com.example.project.entity.IssueNotification;
import com.example.project.entity.User;
import com.example.project.mapper.IssueCommentMapper;
import com.example.project.service.CommonService;
import com.example.project.service.IssueCommentService;
import com.example.project.service.IssueNotificationService;

/**
 * 需求评论服务实现类
 */
@Service
public class IssueCommentServiceImpl implements IssueCommentService {

	@Autowired
	private IssueCommentMapper commentMapper;

	@Autowired
	private IssueNotificationService notificationService;

	@Autowired
	private CommonService commonService;

	// 以下是实现接口方法

	@Override
	public IssueComment selectIssueCommentById(Long id) {
		IssueComment comment = commentMapper.selectById(id);

		if (comment != null) {
			// 获取附件
			List<IssueCommentAttachment> attachments = commentMapper.getAttachmentsByCommentId(id);
			comment.setAttachments(attachments);
		}

		return comment;
	}

	@Override
	public List<IssueComment> selectIssueCommentList(IssueComment issueComment) {
		// 根据条件查询评论列表
		return commentMapper.getCommentsByConditions(new HashMap<>());
	}

	@Override
	public List<IssueComment> selectCommentsByIssueId(Long issueId, Boolean includeInternal) {
		// 获取所有评论
		List<IssueComment> allComments = commentMapper.getCommentsByIssueId(issueId);

		if (CollectionUtils.isEmpty(allComments)) {
			return new ArrayList<>();
		}

		// 如果不包含内部评论，则过滤掉内部评论
		if (includeInternal != null && !includeInternal) {
			allComments.removeIf(comment -> comment.getIsInternal() != null && comment.getIsInternal() == 1);
		}

		// 获取所有附件
		Map<Long, List<IssueCommentAttachment>> attachmentMap = new HashMap<>();
		for (IssueComment comment : allComments) {
			List<IssueCommentAttachment> attachments = commentMapper.getAttachmentsByCommentId(comment.getId());
			attachmentMap.put(comment.getId(), attachments);

			Long authorId = comment.getAuthorId();
			User userInfo = commonService.getUserInfo(authorId);
			comment.setUserName(userInfo != null ? userInfo.getUserName() : "");
			comment.setUserAvatar(userInfo != null ? userInfo.getAvatar() : "");
		}

		// 设置附件到评论中
		for (IssueComment comment : allComments) {
			comment.setAttachments(attachmentMap.get(comment.getId()));
		}

		// 构建评论树
		return buildCommentTree(allComments);
	}

	@Override
	@Transactional
	public int insertIssueComment(IssueComment issueComment) {
		// 设置创建时间
		issueComment.setCreatedTime(LocalDateTime.now());

		// 插入评论
		return commentMapper.insert(issueComment);
	}

	@Override
	@Transactional
	public int updateIssueComment(IssueComment issueComment) {
		// 设置更新时间
		issueComment.setUpdatedTime(LocalDateTime.now());

		// 更新评论
		return commentMapper.updateById(issueComment);
	}

	@Override
	@Transactional
	public int deleteIssueCommentByIds(Long[] ids) {
		int count = 0;
		for (Long id : ids) {
			count += deleteIssueCommentById(id);
		}
		return count;
	}

	@Override
	@Transactional
	public int deleteIssueCommentById(Long id) {
		// 删除评论附件
		commentMapper.deleteAttachmentsByCommentId(id);

		// 删除评论
		return commentMapper.deleteById(id);
	}

	@Override
	@Transactional
	public boolean addCommentWithNotification(IssueComment issueComment, List<Long> notifiedUsers) {
		// 设置创建时间
		issueComment.setCreatedTime(LocalDateTime.now());

		// 插入评论
		int result = commentMapper.insert(issueComment);
		if (result <= 0) {
			return false;
		}

		// 创建通知
		if (notifiedUsers != null && !notifiedUsers.isEmpty()) {
			for (Long userId : notifiedUsers) {
				IssueNotification notification = new IssueNotification();
				notification.setIssueId(issueComment.getIssueId());
				notification.setReceiverId(userId);
				notification.setNotificationType(getNotificationTypeCode("comment"));
				notification.setTitle("需求有新评论");
				notification.setContent("您关注的需求有新评论：" + issueComment.getContent());
				notification.setSenderId(issueComment.getAuthorId());
				notification.setCreateTime(LocalDateTime.now());
				notification.setIsRead(0);

				notificationService.insertIssueNotification(notification);
			}
		}

		return true;
	}

	// 以下是新增的辅助方法

	/**
	 * 添加评论（带附件）
	 */
	@Transactional
	public IssueComment addComment(IssueComment comment, List<IssueCommentAttachment> attachments) {
		// 设置评论信息
		comment.setCreatedTime(LocalDateTime.now());

		// 保存评论
		commentMapper.insert(comment);

		// 保存附件
		if (!CollectionUtils.isEmpty(attachments)) {
			for (IssueCommentAttachment attachment : attachments) {
				commentMapper.insertAttachment(comment.getId(), attachment.getFileName(), attachment.getFilePath(),
						attachment.getFileSize(), attachment.getContentType());
			}
		}

		// 创建通知
		createCommentNotification(comment);

		return comment;
	}

	/**
	 * 根据需求ID获取评论列表（包含所有评论）
	 */
	public List<IssueComment> getCommentsByIssueId(Long issueId) {
		return selectCommentsByIssueId(issueId, true);
	}

	/**
	 * 更新评论
	 */
	@Transactional
	public boolean updateComment(IssueComment comment) {
		comment.setUpdatedTime(LocalDateTime.now());
		return commentMapper.updateById(comment) > 0;
	}

	/**
	 * 删除评论
	 */
	@Transactional
	public boolean deleteComment(Long commentId) {
		return deleteIssueCommentById(commentId) > 0;
	}

	/**
	 * 根据ID获取评论
	 */
	public IssueComment getCommentById(Long commentId) {
		return selectIssueCommentById(commentId);
	}

	/**
	 * 根据用户ID获取评论列表
	 */
	public List<IssueComment> getCommentsByUserId(Long userId) {
		return commentMapper.getCommentsByAuthorId(userId);
	}

	/**
	 * 获取评论数量
	 */
	public int getCommentCountByIssueId(Long issueId) {
		return commentMapper.countCommentsByIssueId(issueId);
	}

	/**
	 * 获取最新评论
	 */
	public List<IssueComment> getLatestComments(Integer limit) {
		return commentMapper.getLatestComments(limit);
	}

	/**
	 * 获取项目评论统计
	 */
	public Map<String, Object> getCommentStatsByProjectId(Long projectId) {
		return commentMapper.getCommentStatsByProjectId(projectId);
	}

	/**
	 * 构建评论树
	 * 
	 * @param allComments 所有评论
	 * @return 评论树
	 */
	private List<IssueComment> buildCommentTree(List<IssueComment> allComments) {
		if (CollectionUtils.isEmpty(allComments)) {
			return new ArrayList<>();
		}

		// 创建评论ID到评论的映射
		Map<Long, IssueComment> commentMap = new HashMap<>();
		for (IssueComment comment : allComments) {
			commentMap.put(comment.getId(), comment);
			// 初始化子评论列表
			comment.setReplies(new ArrayList<>());
		}

		// 构建树结构
		List<IssueComment> rootComments = new ArrayList<>();
		for (IssueComment comment : allComments) {
			if (comment.getParentId() == null || comment.getParentId() == 0L) {
				// 根评论
				rootComments.add(comment);
			} else {
				// 子评论
				IssueComment parentComment = commentMap.get(comment.getParentId());
				if (parentComment != null) {
					parentComment.getReplies().add(comment);
				}
			}
		}

		return rootComments;
	}

	/**
	 * 创建评论通知
	 * 
	 * @param comment 评论
	 */
	private void createCommentNotification(IssueComment comment) {
		// 获取被@的用户
		List<Long> mentionedUserIds = extractMentionedUsers(comment.getContent());

		// 创建通知给被@的用户
		for (Long userId : mentionedUserIds) {
			IssueNotification notification = new IssueNotification();
			notification.setIssueId(comment.getIssueId());
			notification.setReceiverId(userId);
			notification.setNotificationType(getNotificationTypeCode("mention"));
			notification.setTitle("您在评论中被提及");
			String content = comment.getContent();
			if (content.length() > 100) {
				content = content.substring(0, 100) + "...";
			}
			notification.setContent("您在需求评论中被提及：" + content);
			notification.setSenderId(comment.getAuthorId());
			notification.setCreateTime(LocalDateTime.now());
			notification.setIsRead(0);

			notificationService.insertIssueNotification(notification);
		}

		// 创建通知给需求作者和指派人（如果不是评论作者本人）
		// 注意：这里需要获取需求的详细信息，在实际实现中应该注入IssueService或IssueMapper
		// 为了简化，这里只创建通知给被@的用户
	}

	/**
	 * 从评论内容中提取被@的用户
	 * 
	 * @param content 评论内容
	 * @return 被@的用户ID列表
	 */
	private List<Long> extractMentionedUsers(String content) {
		List<Long> mentionedUserIds = new ArrayList<>();

		if (StringUtils.hasText(content)) {
			// 简单实现，提取@后面的数字
			String[] parts = content.split("@");
			for (int i = 1; i < parts.length; i++) {
				String part = parts[i];
				if (part.length() > 0) {
					// 提取数字部分
					StringBuilder numStr = new StringBuilder();
					for (char c : part.toCharArray()) {
						if (Character.isDigit(c)) {
							numStr.append(c);
						} else {
							break;
						}
					}

					if (numStr.length() > 0) {
						try {
							Long userId = Long.parseLong(numStr.toString());
							mentionedUserIds.add(userId);
						} catch (NumberFormatException e) {
							// 忽略解析错误
						}
					}
				}
			}
		}

		return mentionedUserIds;
	}

	/**
	 * 将通知类型字符串转换为对应的整数代码
	 * 
	 * @param typeStr 通知类型字符串
	 * @return 通知类型代码
	 */
	private Integer getNotificationTypeCode(String typeStr) {
		if ("comment".equals(typeStr)) {
			return 1; // 1-评论
		} else if ("status_change".equals(typeStr)) {
			return 2; // 2-状态变更
		} else if ("assignment".equals(typeStr)) {
			return 3; // 3-分配
		} else if ("mention".equals(typeStr)) {
			return 4; // 4-提醒
		}
		return 1; // 默认为评论类型
	}
}
